﻿// -----------------------------------------------------------------------
// <copyright file="MyVisitor.cs" company="none">
// Copyright (c) 2012 M. Alberti, xanatos(at)live.it
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// </copyright>
// -----------------------------------------------------------------------

namespace FluentStatement.Sample
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    /// <summary>
    /// 
    /// </summary>
    public class MyVisitor : Visitor
    {
        /// <summary>
        /// 
        /// </summary>
        protected static readonly MethodInfo ConsoleWriteLine = typeof(MyStatement).GetMethod("ConsoleWriteLine");

        /// <summary>
        /// 
        /// </summary>
        /// <param name="declaringType"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        protected override bool ProcessMethodCall(Type declaringType, MethodInfo method)
        {
            return declaringType == typeof(MyStatement) || base.ProcessMethodCall(declaringType, method);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <param name="declaringType"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        protected override Expression VisitStatementMethod(MethodCallExpression node, Type declaringType, MethodInfo method)
        {
            if (method == ConsoleWriteLine)
            {
                var writeLine = typeof(Console).GetMethod("WriteLine", new[] { typeof(string) });
                return Expression.Call(writeLine, this.Visit(node.Arguments[1]));
            }

            return base.VisitStatementMethod(node, declaringType, method);
        }
    }
}
